package org.yanwensiyi.maomamabot.bot

import net.mamoe.mirai.event.events.FriendMessageEvent
import net.mamoe.mirai.event.events.GroupMessageEvent
import net.mamoe.mirai.event.events.GroupTempMessageEvent
import net.mamoe.mirai.event.events.MessageEvent
import org.graalvm.polyglot.Context
import java.util.concurrent.ArrayBlockingQueue

class Dispatcher(val bot: Bot) : Thread() {
    companion object {
        val queue = ArrayBlockingQueue<MessageEvent>(11451)
        fun <T : MessageEvent> offer(event: T) {
            when (event) {
                is GroupMessageEvent -> {}
                is FriendMessageEvent -> {}
                is GroupTempMessageEvent -> {}
                else -> {}
            }
        }
    }

    enum class State {
        INITIALIZING,
        SERVING,
        CLOSED
    }

    private lateinit var scriptContext: Context

    @Volatile
    private var state = State.INITIALIZING

    init {
        initScriptContext()
        start()
    }

    /**
     * dispatcher工作主循环
     */
    override fun run() {
        while (true) {
            when (state) {
                State.INITIALIZING -> try {
                    sleep(100)
                } catch (_: Throwable) {
                }


                State.SERVING -> {

                }

                State.CLOSED -> return
            }
        }
    }

    @Volatile
    var lastInitTime = 0L

    /**
     * 初始化脚本上下文
     * @param time 操作时间，两次重新初始化操作过短会被忽略
     */
    @Synchronized
    fun initScriptContext(time: Long = System.currentTimeMillis()) {
        //距离上次加载时间太短
        if (time - lastInitTime < 1145) {
            return
        }
        state = State.INITIALIZING
        //第一次初始化的时候跳过close
        if (lastInitTime != 0L) {
            while (true) {
                try {
                    scriptContext.close()
                    break
                } catch (_: Throwable) {
                    sleep(100)
                }
            }
        }
        lastInitTime = time
        //重新创建上脚本下文
        scriptContext = Context.newBuilder("js").allowAllAccess(true).build()!!
        scriptContext.getBindings("js").putMember("bot", bot)
        //恢复状态
        state = State.SERVING
    }
}